package org.example.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.domain.Member;
import org.example.model.Result;
import org.example.service.MemberService;
import org.example.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "微信小程序会员接口管理")
@RestController
@RequestMapping("p/user")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @ApiOperation("查看会员的头像和昵称")
    @GetMapping("/getUserInfo")
    public Map checkMemberInfo() {
        String openId = AuthUtils.getMemberOpenId();
        Member userInfo = memberService.checkMemberInfoByOpenId(openId);
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtil.isNotNull(userInfo)){
            map.put("data",userInfo);
            map.put("code", 200);
            map.put("message", "ok");
        }else{
            map.put("code", 500);
            map.put("message", "用户信息获取失败");
            map.put("data", null);
        }
        return map;
    }

    @ApiOperation("更新会员的头像和昵称")
    @PutMapping("/setUserInfo")
    public Map modifyMemberInfo(@RequestBody Member member) {
        Member modified = memberService.modifyMemberInfoByOpenId(member);

        Map<String, Object> map = new HashMap<>();
        if (ObjectUtil.isNull(modified)){
            map.put("code", 500);
            map.put("message", "用户信息更新失败");
            map.put("data", null);
            return map;
        }
        map.put("data",modified );
        map.put("code", 200);
        map.put("message", "ok");

        return map;
    }

    @ApiOperation("查询会员是否绑定手机号码")
    @GetMapping("/isBindPhone")
    public Result<Boolean> loadMemberIsBindPhone() {
        // 获取会员的openid
        String openId = AuthUtils.getMemberOpenId();
        // 根据会员openid查询会员详情
        Member member = memberService.getOne( new LambdaQueryWrapper<Member>()
                .eq(Member::getOpenId, openId)
        );
        return Result.success( StringUtils.hasText(member.getUserMobile()));
    }

    // TODO: 2025/11/05 feign接口调用

    @GetMapping("getMemberListByOpenIds")
    public Result<List<Member>> getMemberListByOpenIds(@RequestParam List<String> openIds){
        List<Member> list =memberService.list(new LambdaQueryWrapper<Member>()
                .in( Member::getOpenId,openIds));
        return Result.success( list);
    }

}
